package com.clduo.test.myexpandabledemo.refresh;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.Scroller;
import android.widget.TextView;

import com.clduo.test.myexpandabledemo.R;

/** 刷新控制view
 * 
 * @author Mr.Sun */
public class RefreshableView extends LinearLayout {

	private static final String TAG = "LILITH";
	private Scroller scroller;
	private View refreshView;
	private ImageView refreshIndicatorView;
	private boolean refreshIndicatorView_rotate = true;
	private int refreshTargetTop;
	private ProgressBar bar;
	private TextView downTextView;
	private TextView timeTextView;
	private TextView refresh_time;
	private RefreshListener refreshListener;

	private Long refreshTime = null;
	private int lastX;
	private int lastY;
	// 拉动标记
	private boolean isDragging = false;
	// 是否可刷新标记
	private boolean isRefreshEnabled = true;
	// 在刷新中标记
	private boolean isRefreshing = false;

	private Context mContext;
	private RotateAnimation _RotateAnimation;

	public RefreshableView(Context context) {
		super(context);
		mContext = context;

	}

	/** 根据手机的分辨率从 dp 的单位 转成为 px(像素) */
	public static float dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (dpValue * scale + 0.5f);
	}

	public RefreshableView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		refreshTargetTop = -(int) dip2px(mContext, 60);
		init();

	}

	private void init() {
		//滑动对象，
		scroller = new Scroller(mContext);
		//刷新视图顶端的的view
		refreshView = LayoutInflater.from(mContext).inflate(R.layout.refresh_top_item, null);
		//指示器view
		refreshIndicatorView = (ImageView) refreshView.findViewById(R.id.indicator);
		//刷新bar
		bar = (ProgressBar) refreshView.findViewById(R.id.progress);
		//下拉显示text
		downTextView = (TextView) refreshView.findViewById(R.id.refresh_hint);
		//显示当前时间时间
		timeTextView = (TextView) refreshView.findViewById(R.id.now_time);
		//上次刷新时间
		refresh_time = (TextView) refreshView.findViewById(R.id.refresh_time);
		LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, -refreshTargetTop);
		lp.topMargin = refreshTargetTop;
		lp.gravity = Gravity.CENTER;
		addView(refreshView, lp);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {

		int y = (int) event.getRawY();

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			//记录下y坐标
			lastY = y;
			break;

		case MotionEvent.ACTION_MOVE:
			//y移动坐标
			int m = y - lastY;
			if (((m < 6) && (m > -1)) || (!isDragging)) {
				doMovement(m);
			}
			//记录下此刻y坐标
			this.lastY = y;
			break;

		case MotionEvent.ACTION_UP:
			fling();

			break;
		}
		return true;
	}

	/** up事件处理 */
	private void fling() {
		LinearLayout.LayoutParams lp = (LayoutParams) refreshView.getLayoutParams();
		if (lp.topMargin > 0) {//拉到了触发可刷新事件
			refresh();
		} else {
			returnInitState();
		}
	}

	private void returnInitState() {
		LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) this.refreshView.getLayoutParams();
		int i = lp.topMargin;
		scroller.startScroll(0, i, 0, refreshTargetTop);
		invalidate();
	}

	private void refresh() {
		LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) this.refreshView.getLayoutParams();
		int i = lp.topMargin;
		refreshIndicatorView.setVisibility(View.GONE);
		bar.setVisibility(View.VISIBLE);
		timeTextView.setVisibility(View.GONE);
		downTextView.setText("正在刷新...");
		scroller.startScroll(0, i, 0, 0 - i);
		invalidate();
		if (refreshListener != null) {
			refreshListener.onRefresh(this);
			isRefreshing = true;
		}
	}

	/**
	 * 
	 */
	@Override
	public void computeScroll() {
		if (scroller.computeScrollOffset()) {
			int i = this.scroller.getCurrY();
			LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) this.refreshView.getLayoutParams();
			int k = Math.max(i, refreshTargetTop);
			lp.topMargin = k;
			this.refreshView.setLayoutParams(lp);
			this.refreshView.invalidate();
			invalidate();
		}
	}

	/** 下拉move事件处理
	 * @param moveY */
	private void doMovement(int moveY) {
		LinearLayout.LayoutParams lp = (LayoutParams) refreshView.getLayoutParams();
		//		if (moveY > 0) {
		//获取view的上边距
		float f1 = lp.topMargin;
		float f2 = moveY * 0.3F;
		int i = (int) (f1 + f2);
		//修改上边距
		lp.topMargin = i;
		//修改后刷新
		refreshView.setLayoutParams(lp);
		refreshView.invalidate();
		invalidate();
		//		}
		timeTextView.setVisibility(View.VISIBLE);
		setNowTime(System.currentTimeMillis());
		downTextView.setVisibility(View.VISIBLE);
		refreshIndicatorView.setVisibility(View.VISIBLE);
		bar.setVisibility(View.GONE);
		if (lp.topMargin > 0) {
			downTextView.setText("松开刷新");
			if (refreshIndicatorView_rotate) {
				refreshIndicatorView_rotate = false;
				_RotateAnimation = new RotateAnimation(0f, -180f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
				AnimationSet _AnimationSet = new AnimationSet(true);
				_AnimationSet.addAnimation(_RotateAnimation);
				_AnimationSet.setFillAfter(true);
				_AnimationSet.setDuration(400);
				refreshIndicatorView.startAnimation(_AnimationSet);//开始上面蓝色横条图片的动画切换  
			}
		} else {
			downTextView.setText("下拉刷新");
			if (!refreshIndicatorView_rotate) {
				refreshIndicatorView_rotate = true;
				_RotateAnimation = new RotateAnimation(-180f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
				AnimationSet _AnimationSet = new AnimationSet(true);
				_AnimationSet.addAnimation(_RotateAnimation);
				_AnimationSet.setFillAfter(true);
				_AnimationSet.setDuration(400);
				refreshIndicatorView.startAnimation(_AnimationSet);//开始上面蓝色横条图片的动画切换  
			}
		}

	}

	public void setRefreshEnabled(boolean b) {
		this.isRefreshEnabled = b;
	}

	public void setRefreshListener(RefreshListener listener) {
		this.refreshListener = listener;
	}

	/** 显示当前时间 */
	private void setNowTime(Long time) {
		Date date = new Date(time);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String str = format.format(date);
		timeTextView.setText("当前时间:" + str);
	}

	/** 显示上次刷新时间 */
	private void setRefreshTime(Long time) {
		Date date = new Date(time);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String str = format.format(date);
		refresh_time.setText("最近更新:" + str);
	}

	/** 结束刷新事件 */
	public void finishRefresh() {
		LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) this.refreshView.getLayoutParams();
		int i = lp.topMargin;
		_RotateAnimation = new RotateAnimation(-180f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
		AnimationSet _AnimationSet = new AnimationSet(true);
		_AnimationSet.addAnimation(_RotateAnimation);
		_AnimationSet.setFillAfter(true);
		_AnimationSet.setDuration(0);
		refreshIndicatorView.setAnimation(_AnimationSet);
		timeTextView.setVisibility(View.GONE);
		setRefreshTime(System.currentTimeMillis());
		scroller.startScroll(0, i, 0, refreshTargetTop);
		invalidate();
		isRefreshing = false;
		refreshIndicatorView_rotate = true;
	}

	/** 该方法一般和ontouchEvent 一起用 (non-Javadoc)
	 * @see android.view.ViewGroup#onInterceptTouchEvent(android.view.MotionEvent) */
	@Override
	public boolean onInterceptTouchEvent(MotionEvent e) {
		// TODO Auto-generated method stub
		int action = e.getAction();
		int y = (int) e.getRawY();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			lastY = y;
			break;

		case MotionEvent.ACTION_MOVE:
			//y移动坐标
			int m = y - lastY;

			//记录下此刻y坐标
			this.lastY = y;
			if (m > 6 && canScroll()) {
				return true;
			}
			break;
		case MotionEvent.ACTION_UP:

			break;

		case MotionEvent.ACTION_CANCEL:

			break;
		}
		return false;
	}

	private boolean canScroll() {
		View childView;
		if (getChildCount() > 1) {
			childView = this.getChildAt(1);
			if (childView instanceof ListView) {
				int top = ((ListView) childView).getChildAt(0).getTop();
				int pad = ((ListView) childView).getListPaddingTop();
				if ((Math.abs(top - pad)) < 3 && ((ListView) childView).getFirstVisiblePosition() == 0) {
					return true;
				} else {
					return false;
				}
			} else if (childView instanceof ScrollView) {
				if (((ScrollView) childView).getScrollY() == 0) {
					return true;
				} else {
					return false;
				}
			}

		}
		return false;
	}

	/** 刷新监听接口
	 * @author Nono */
	public interface RefreshListener {
		public void onRefresh(RefreshableView view);
	}

}
